<?php

/**
 * This is the model class for table "cardreq".
 *
 * The followings are the available columns in table 'cardreq':
 * @property integer $_id
 * @property integer $insertTime
 * @property integer $updateTime
 * @property integer $ownerId
 * @property integer $dateTime
 * @property string $status
 * @property string $message
 * @property string $memberCodes
 */
class Cardreq extends ActiveRecord {

	const STATUS_DRAFT = 'Draft';
	const STATUS_SENT = 'Sent';
	const STATUS_DONE = 'Done';

	public $file;

	/**
	 * Returns the static model of the specified AR class.
	 * @return Cardreq the static model class
	 */
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'cardreq';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('message, memberCodes', 'required'),
			array('memberCodes', 'isExists'),
			array(
				'file',
				'file',
				'types'=>'jpg, gif, png',
				'maxSize'=>10485760,
				'on'=>'insert',
			),
			array(
				'file',
				'file',
				'types'=>'jpg, gif, png',
				'maxSize'=>10485760,
				'on'=>'update',
				'allowEmpty'=>true,
			),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * Check member codes existence in database.
	 * @param type $attribute
	 * @param type $params
	 */
	public function isExists($attribute, $params) {
		if (!$this->$attribute) return;
		$code = trim(str_replace('?', '', $this->$attribute));
		$codes = explode("\r\n", $code);
		$missings = array();
		$finder = Member::model();
		for ($index = 0; $index < count($codes); $index++) {
			$criteria = new CDbCriteria;
			$data = explode(' ', $codes[$index]);
			$criteria->compare('code', $data[0], false);
			if (!$finder->exists($criteria)) {
				$error = $this->getAttributeLabel($attribute) . ' "';
				$error .= $codes[$index] . '" [baris ' . ($index + 1) . ']';
				$error .= ' tidak ditemukan di database.';
				$missings[] = $error;
				$codes[$index] = '?' . $data[0];
			} else {
				$model = $finder->find($criteria);
				$codes[$index] = $data[0] . " <$model->name>";
			}
		}
		if ($missings) {
			$this->addErrors(array($attribute=>$missings));
		}
		$this->$attribute = implode("\r\n", $codes);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'status'=>'Status',
			'message'=>'Pesan',
			'memberCodes'=>'No Reg',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search() {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('status', $this->status, true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}

	public function getStatusList() {
		return array(
			self::STATUS_DRAFT,
			self::STATUS_SENT,
			self::STATUS_DONE,
		);
	}

	/**
	 * @return boolean
	 */
	protected function beforeSave() {
		if (!parent::beforeSave()) return false;
		$this->file = CUploadedFile::getInstance($this, 'file');
		return true;
	}

	/**
	 * If scenario is insert then save the uploaded image
	 */
	protected function afterSave() {
		parent::afterSave();
		if ($this->file) {
			// We must save the uploaded file here because path depends on _id
			// and _id only exist after saving.
			$image = new ImageFile($this->file->tempName);
			$folder = Yii::app()->params['image']['cardreq'];
			if (!is_dir("$folder/$this->folder")) {
				mkdir("$folder/$this->folder");
			}
			$path = "$folder/$this->path";
			$image->saveAsJpeg($path);
		}
	}

	/**
	 * Delete image if exists
	 */
	protected function afterDelete() {
		parent::afterDelete();
		$folder = Yii::app()->params['cardreqImage'];
		$path = "$folder/$this->path";
		if (is_file($path)) unlink($path);
	}

	/**
	 * @property integer number of subfolder of the id
	 */
	public function getFolder() {
		return intval($this->_id / 1000);
	}

	/**
	 * @property string $path absolute location of the image file
	 */
	public function getPath() {
		return "$this->folder/$this->_id.jpg";
	}

}